﻿// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 
// See License.txt in the project root for license information.


namespace ActorGatewayService
{
    using System;
    using System.Diagnostics.Contracts;
    using System.Globalization;
    using System.IO;

    public static class MessageLogger
    {
        private static StreamWriter writer;

        public static void Initialize(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (writer != null)
            {
                writer.Close();
                writer = null;
            }

            writer = new StreamWriter(fileName, true); // Append if we've restarted the service
        }

        public static void Write(string text)
        {
            if (writer == null)
            {
                throw new ApplicationException("Call initialize before calling this method.");
            }

            Console.Write(text);
            writer.Write(text);
            writer.Flush();
        }

        public static void WriteLine(string text)
        {
            if (writer == null)
            {
                throw new ApplicationException("Call initialize before calling this method.");
            }

            Console.WriteLine(text);
            writer.WriteLine(DateTime.Now.ToString("s") + ": " + text);
            writer.Flush();
        }

        public static void Write(string format, params object[] arg)
        {
            Contract.Requires(format != null);
            Contract.Requires(arg != null);

            string text = string.Format(CultureInfo.InvariantCulture, format, arg);
            Write(text);
        }

        public static void WriteLine(string format, params object[] arg)
        {
            Contract.Requires(format != null);
            Contract.Requires(arg != null);

            string text = string.Format(CultureInfo.InvariantCulture, format, arg);
            WriteLine(text);
        }

        public static void WriteLine()
        {
            WriteLine("\n");
        }

        public static void Close()
        {
            if (writer != null)
            {
                writer.Close();
                writer = null;
            }
        }
    }
}
